#include "mex.h"
#include "EvolutiveLib.h"
#include "IntSamplesSet.h"

using namespace Evolutive;

void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray*prhs[])    
{ 		
	CIntSamplesSet SamplesSet;
	CvSize ImgSize;

	/*! InputParameters:
		FileName: File that contains the Integral Images set.		
	*/
	string FileName;	
	        
	/*! OutputParameters:
		NumSamples: Number of samples in the samples set
		SamplesSize: Size of the samples
		ExpectedVal: Expected values
	*/
	double *pNumSamples=NULL;
	double *pSamplesSize=NULL;	
	double *pExpectedVals=NULL;
			
	// Verify the input and output parameters
    if (nrhs !=1 || nlhs>3) 
	{ 
		mexErrMsgTxt("Paramters error. [NumSamples,SamplesSize,ExpectedVals]= " \
			"MEXGetSamplesInfo(FileName).\n" \
			"\tFileName: Strings with the filename of the data\n"\
			"\tNumSamples: Number of samples.\n" \
			"\tSamplesSize: Size of the samples. Vector 1x2.\n" \
			"\tExpectedVals: Expected values for each sample. Vector 1xNumSamples. \n");
	}

	// Verify the type of input parameters
	if(!mxIsChar(prhs[0]))
		mexErrMsgTxt("Parameters type error. The FileName must be a string"); 
				
	// Point to the images filename
	FileName=(char*)mxArrayToString(prhs[0]);	
		
	// Load the image samples		
	try
	{
		// Training set
		SamplesSet.Load(FileName);
	}
	catch(CEvolutiveLibException e)
	{
		mexErrMsgTxt((const char*)(e.ToString()).data());
	}
	catch(exception e)
	{
		mexErrMsgTxt(e.what());
	}

	// Create the output data and point it
	// NumSamples
	plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);		
	pNumSamples=(double*)mxGetPr(plhs[0]);
	pNumSamples[0]=SamplesSet.GetNumSamples();

	// SamplesSize
	if(nlhs>1)
	{
		// Obtain the samples size
		ImgSize=SamplesSet.GetSamplesSize();
		
		// Create the matrix
		plhs[1] = mxCreateDoubleMatrix(1,2,mxREAL);
		pSamplesSize=(double*)mxGetPr(plhs[1]);

		// Store the data
		pSamplesSize[0]=ImgSize.width;
		pSamplesSize[1]=ImgSize.height;
	}
	
	// ExpectedVals
	if(nlhs>1)
	{
		// Create the matrix
		plhs[2] = mxCreateDoubleMatrix(1,SamplesSet.GetNumSamples(),mxREAL);
		pExpectedVals=(double*)mxGetPr(plhs[2]);

		// Store the data
		for(int i=0;i<SamplesSet.GetNumSamples();i++)
			pExpectedVals[i]=SamplesSet.ExpectedVal(i);
	}

    return;    
}
